package vip.zhenzicheng.concurrent_program.thread.sgg.completablefuture;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 电商比价demo
 *
 * @author zhenzicheng
 * @date 2022-06-10 19:18
 */
public class CompletableFutureMallDemo {
  static List<NetMall> list = new ArrayList<>();

  static {
    list.addAll(Arrays.asList(
        new NetMall("jd"),
        new NetMall("dangdang"),
        new NetMall("taobao"),
        new NetMall("pdd"),
        new NetMall("taote"),
        new NetMall("meituandianshagn"),
        new NetMall("huaweishagncheng")
    ));
  }

  public static List<String> getPrice(List<NetMall> list, String productName) {
    return list.stream()
        .map(netMall -> String.format(productName + "in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName)))
        .collect(Collectors.toList());
  }

  public static List<String> getPriceByCompletableFuture(List<NetMall> list, String productName) {
    return list.stream()
        .map(netMall ->
            CompletableFuture.supplyAsync(
                () -> String.format(productName + "in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName))))
        .collect(Collectors.toList())
        .stream()
        .map(s -> s.join())
        .collect(Collectors.toList());
  }

  public static void main(String[] args) {
    // CompletableFuture.runAsync().thenRun();
    // CompletableFuture.thenRun()
    // 常规方法
    long s = System.currentTimeMillis();
    // getPrice(list, "IPhone 13 Pro Max");
    getPriceByCompletableFuture(list, "IPhone 13 Pro Max");
    long e = System.currentTimeMillis();
    System.out.println("----costTime:" + (e - s) + "毫秒");
  }


}

@AllArgsConstructor
@Data
class NetMall {

  private String netMallName;

  public double calcPrice(String productName) {
    try {
      TimeUnit.MILLISECONDS.sleep(400);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
  }

}
